﻿using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Xioa_UI.Message;

namespace Xioa_UI.Controls;

[TemplatePart(Name = "PART_PanelTop", Type = typeof(Panel))]
[TemplatePart(Name = "PART_ImageViewer", Type = typeof(XioaImageViewer))]
[TemplatePart(Name = "PART_CloseButton", Type = typeof(Button))]
[TemplatePart(Name = "Print_Button", Type = typeof(Button))]
public class XioaImageBrowser : XioaWindow
{
    private const string ElementPanelTop = "PART_PanelTop";
    private const string ElementImageViewer = "PART_ImageViewer";
    private const string PartCloseButton = "PART_CloseButton";
    private const string PrintButton = "Print_Button";

    #region Data

    private Panel? _panelTop;
    private XioaImageViewer? _imageViewer;
    private Button? _closeButton;
    private Button? _printButton;

    #endregion Data

    public static readonly DependencyProperty IsFullScreenProperty = DependencyProperty.Register(
        "IsFullScreen", typeof(bool), typeof(XioaImageBrowser),
        new PropertyMetadata(false));

    public bool IsFullScreen
    {
        get => (bool)GetValue(IsFullScreenProperty);
        set => SetValue(IsFullScreenProperty, value);
    }

    static XioaImageBrowser()
    {
    }

    public XioaImageBrowser()
    {
        WindowStartupLocation = WindowStartupLocation.CenterScreen;
        WindowStyle = WindowStyle.None;
        AllowsTransparency = true;
    }

    /// <summary>
    ///     带一个图片Uri的构造函数
    /// </summary>
    /// <param name="uri"></param>
    public XioaImageBrowser(Uri uri) : this()
    {
        Loaded += (s, e) =>
        {
            try
            {
                if (_imageViewer is null) return;
                _imageViewer.ImageSource = BitmapFrame.Create(uri);
                _imageViewer.ImgPath = uri.AbsolutePath;

                if (File.Exists(_imageViewer.ImgPath))
                {
                    var info = new FileInfo(_imageViewer.ImgPath);
                    _imageViewer.ImgSize = info.Length;
                }
            }
            catch
            {
                XioaMessageBox.Show("ErrorImgPath");
            }
        };
    }

    /// <summary>
    ///     带一个图片Uri的构造函数
    /// </summary>
    /// <param name="uri"></param>
    /// <param name="imagesource"></param>
    public XioaImageBrowser(BitmapSource imagesource) : this()
    {
        Loaded += (s, e) =>
        {
            try
            {
                if (_imageViewer is null) return;

                this.PixelHeight = imagesource.PixelHeight;
                this.PixelWidth = imagesource.PixelWidth;
                _imageViewer.PixelHeight = imagesource.PixelHeight;
                _imageViewer.PixelWidth = imagesource.PixelWidth;
                _imageViewer.ImageSource = BitmapFrame.Create(imagesource);
            }
            catch
            {
                XioaMessageBox.Show("ErrorImageSourcePath");
            }
        };
    }

    /// <summary>
    ///     带一个图片路径的构造函数
    /// </summary>
    /// <param name="path"></param>
    public XioaImageBrowser(string path) : this(new Uri(path))
    {
    }

    public override void OnApplyTemplate()
    {
        if (_panelTop != null)
        {
            _panelTop.MouseLeftButtonDown -= PanelTopOnMouseLeftButtonDown;
        }

        if (_imageViewer != null)
        {
            _imageViewer.MouseLeftButtonDown -= ImageViewer_MouseLeftButtonDown;
        }

        if (_printButton != null)
        {
            _printButton.Click -= Print_Button_OnClick;
        }

        if (_closeButton != null)
        {
            _closeButton.Click -= ButtonClose_OnClick;
        }

        base.OnApplyTemplate();

        _panelTop = GetTemplateChild(ElementPanelTop) as Panel;
        _imageViewer = GetTemplateChild(ElementImageViewer) as XioaImageViewer;
        _closeButton = GetTemplateChild(PartCloseButton) as Button;
        _printButton = GetTemplateChild(PrintButton) as Button;

        if (_panelTop != null)
        {
            _panelTop.MouseLeftButtonDown += PanelTopOnMouseLeftButtonDown;
        }

        if (_imageViewer != null)
        {
            _imageViewer.MouseLeftButtonDown += ImageViewer_MouseLeftButtonDown;
        }

        if (_closeButton != null)
        {
            _closeButton.Click += ButtonClose_OnClick;
        }

        if (_printButton != null)
        {
            _printButton.Click += Print_Button_OnClick;
        }
    }

    private void Print_Button_OnClick(object sender, RoutedEventArgs e)
    {
        if (_imageViewer is null) return;
        var view = new PrintDialog
        {
            SelectedPagesEnabled = true
        };
        var result = view.ShowDialog();
        if (result is not null && (bool)result)
            view.PrintVisual(_imageViewer, "Print");
    }

    private void ButtonClose_OnClick(object sender, RoutedEventArgs e) => Close();

    private void PanelTopOnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            DragMove();
        }
    }

    private void ImageViewer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed &&
            !(_imageViewer?.ImageWidth > ActualWidth || _imageViewer?.ImageHeight > ActualHeight))
        {
            DragMove();
        }
    }


    internal static readonly DependencyProperty PixelHeightProperty =
        ElementBase.Property<XioaImageBrowser, int>("PixelHeightProperty", 0);

    internal static readonly DependencyProperty PixelWidthProperty =
        ElementBase.Property<XioaImageBrowser, int>("PixelWidthProperty", 0);

    public int PixelHeight
    {
        get => (int)GetValue(PixelHeightProperty);
        set => SetValue(PixelHeightProperty, value);
    }

    public int PixelWidth
    {
        get => (int)GetValue(PixelWidthProperty);
        set => SetValue(PixelWidthProperty, value);
    }
}